package com.scnb.cor;

import java.util.ArrayList;
import java.util.List;

/**
 * 责任链模式
 */

public class Main {
    public static void main(String[] args) {
        Msg msg = new Msg();
        msg.setMsg("大家好:)，<script>，欢迎访问 mashibing.com，大家都是996 ");
        //处理
        FilterChain fc1 = new FilterChain();
        //链式编程
        fc1.add(new HTMLFilter())
                .add(new SensitiveFilter());

        FilterChain fc2 = new FilterChain();
        fc2.add(new FaceFilter())
                .add(new URLFilter());

        fc1.add(fc2);

        fc1.doFilter(msg);

        System.out.println(msg);
    }
}

class Msg{
    String name;
    String msg;

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    @Override
    public String toString() {
        return "Msg{" +
                "msg='" + msg + '\'' +
                '}';
    }
}

interface Filter{
    boolean doFilter(Msg msg);
}

class HTMLFilter implements Filter{

    @Override
    public boolean doFilter(Msg msg) {
        //处理msg
        String r = msg.getMsg();
        r = r.replace('<','[');
        r = r.replace('>',']');
        return true;
    }
}

class SensitiveFilter implements Filter{

    @Override
    public boolean doFilter(Msg msg) {
        String r = msg.getMsg();
        r = r.replaceAll("996", "955");
        msg.setMsg(r);
        return true;
    }
}

class FaceFilter implements Filter{

    @Override
    public boolean doFilter(Msg msg) {
        String r = msg.getMsg();
        r = r.replace(":)", "^V^");
        msg.setMsg(r);
        return true;
    }
}

class URLFilter implements Filter{

    @Override
    public boolean doFilter(Msg msg) {
        String r = msg.getMsg();
        r = r.replaceAll("mashibing.com", "http://www.mashibing.com");
        msg.setMsg(r);
        return true;
    }
}

/**
 * FilterChain实现了Filter接口后，则一个FilterChain对象自己本身
 * 也是一个Filter，那么main函数中执行fc1.add(fc2)就可以了（此时把fc2看做Filter）
 */
class FilterChain implements Filter{
    List<Filter> filters = new ArrayList<>();

    public FilterChain add(Filter f){
        filters.add(f);
        return this;
    }

    public boolean doFilter(Msg msg){
        for (Filter filter : filters){
            if (!filter.doFilter(msg)){
                return false;
            }
        }
        return true;
    }
}
